package com.shang.activemq.tx;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

import static javax.jms.Session.AUTO_ACKNOWLEDGE;

/**
 * 签收和事务的关系
 *      在事务性会话中，当一个事务被成功提交则消息被自动签收。如果事务回滚，则消息会被再次传送
 *
 *      非事务性会话中，消息何时被确认取决于创建会话时的应答模式（ackonwledgement mode）
 */
public class JmsConsumer_tx {

    public static final String ACTIVEMQ_URL = "tcp://192.168.0.113:61616";
    public static final String QUEUE_NAME = "QUEUE01";

    public static void main(String[] args) throws JMSException, IOException {
        //1.创建连接工厂,按照给定的url地址，采用默认用户名和密码
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工厂，获得connection并启动访问
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();
        //3.创建回话session
        //参数：事务 签收
//        Session session = connection.createSession(false, AUTO_ACKNOWLEDGE);
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        //4.创建目的地（具体是队列还是主题topic）
        Queue queue = session.createQueue(QUEUE_NAME);

        //5.创建消费者
        MessageConsumer messageConsumer = session.createConsumer(queue);

        messageConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                if (null != message && message instanceof TextMessage){
                    TextMessage textMessage = (TextMessage) message;
                    try {
                        //手动签收
                        textMessage.acknowledge();
                        System.out.println(textMessage.getText());
                        System.out.println(textMessage.getStringProperty("c01"));
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        System.in.read();

        //顺着申请 倒着关闭
        messageConsumer.close();
        //事务提交
        session.commit();
        session.close();
        connection.close();
    }
}
